package com.wanxi.education.controller.front;

import com.github.pagehelper.PageInfo;
import com.github.wxpay.sdk.WXPayUtil;
import com.wanxi.education.common.CommonResult;
import com.wanxi.education.config.ConfigUtil;
import com.wanxi.education.model.vo.order.*;
import com.wanxi.education.service.OrderFrontService;
import com.wanxi.education.util.CommonUtil;
import io.swagger.annotations.*;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @Author: 寇文宝
 * @Description:
 * @Date: Created in 2021/9/24
 * @Version: 1.0
 */
@Api(tags = "前端订单功能")
@RestController
@RequestMapping("/front/order")
public class OrderFrontController {
    private static final DecimalFormat df = new DecimalFormat("#");

    @Autowired
    private OrderFrontService orderFrontService;

    @ApiOperation("前端订单功能生成订单-----课程详情页面点击报名时传入数据，生成订单后返回数据到确认订单页面")
    @PostMapping("/generateOrder")
    @ApiParam(name = "orderAddVo", value = "生成订单vo类")
    public CommonResult generateOrder(@RequestBody OrderAddVo orderAddVo, HttpSession session) {
        // 用户id从session中自己拿
        Long userId = (Long) session.getAttribute("loginCId");
        if (ObjectUtils.isEmpty(userId)) {
            return CommonResult.unauthorized("未登录");
        }
//        Long userId = 3L;
        orderAddVo.setUserId(userId);
        OrderFindByIdVo orderFindByIdVo = orderFrontService.generateOrder(orderAddVo);
        System.out.println(orderFindByIdVo.toString());
        return CommonResult.success(orderFindByIdVo);
    }

    @ApiOperation("前端订单功能支付界面生成支付二维码")
    @PostMapping("/advancePayment")
    @ApiParam(name = "orderAdvancePaymentVo", value = "订单支付生成支付二维码vo类")
    public CommonResult advancePayment(@RequestBody OrderAdvancePaymentVo orderAdvancePaymentVo, HttpSession session) {
        // 用户id从session中自己拿，拿到订单id去查询价格,订单编号，课程名称生成支付二维码返回给页面
        Long userId = (Long) session.getAttribute("loginCId");
//        Long userId = 1L;
        if (ObjectUtils.isEmpty(userId)) {
            return CommonResult.unauthorized("未登录");
        }
        OrderFindByIdVo byId = orderFrontService.findById(orderAdvancePaymentVo.getId(), userId);
        if (byId.getOrderNumber() == null) {
            return CommonResult.failure("订单信息有误，生成二维码失败");
        }
        try {
            //todo 创建请求参数
            SortedMap<String, String> req = new TreeMap<String, String>();
            req.put("appid", ConfigUtil.APPID);    //公众号
            req.put("body", byId.getCourseName()); // 商品描述
            req.put("mch_id", ConfigUtil.MCH_ID);  // 商户号
            req.put("nonce_str", WXPayUtil.generateNonceStr()); // 32位随机字符串
            req.put("notify_url", "http://hskdemo.natapp1.cc/pay/notify");  // 回调地址
            req.put("out_trade_no", byId.getOrderNumber());   // 商户订单号
//            req.put("spbill_create_ip", CommonUtil.getIp(request));   // 终端IP
            req.put("spbill_create_ip", "222.209.32.93");   // 终端IP
//            req.put("total_fee", df.format(Double.parseDouble(totalFee) * 100));    // 标价金额(分)
            req.put("total_fee", df.format(Double.parseDouble(String.valueOf(1))));    // 标价金额(分)
            req.put("trade_type", "NATIVE");    // 交易类型
//            req.put("sign", WXPayUtil.generateSignature(req, ConfigUtil.API_KEY, WXPayConstants.SignType.MD5));  // 签名

            //todo 生成要发送的 xml
            String xmlBody = WXPayUtil.generateSignedXml(req, ConfigUtil.API_KEY);
            System.err.println(String.format("微信支付预下单请求 xml 格式:\n%s", xmlBody));

            //todo 发送 POST 请求 统一下单 API 并携带 xmlBody 内容,然后获得返回接口结果
            String result = CommonUtil.httpsRequest("https://api.mch.weixin.qq.com/pay/unifiedorder", "POST", xmlBody);
            System.err.println(String.format("%s", result));

            //todo 将返回结果从 xml 格式转换为 map 格式
            Map<String, String> resultMap = WXPayUtil.xmlToMap(result);
            Map<String, String> map = new HashMap<>();
            map.put("code_url", resultMap.get("code_url")); // 支付地址
            map.put("total_fee", df.format(Double.parseDouble(String.valueOf(byId.getPrice())))); // 总金额
            map.put("out_trade_no", byId.getOrderNumber());    // 订单号
            map.put("order_name", byId.getCourseName());    // 商品内容
            return CommonResult.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failure("生成二维码失败");
        }
    }

    @ApiOperation("前端订单功能支付界面确认订单是否支付成功")
    @GetMapping("/searchOrderState")
    @ApiParam(name = "searchOrderStateVo", value = "轮询订单vo类")
    public CommonResult searchOrderState(SearchOrderStateVo searchOrderStateVo, HttpSession session) {
        // 查询订单状态
        Long userId = (Long) session.getAttribute("loginCId");
        if (ObjectUtils.isEmpty(userId)) {
            return CommonResult.unauthorized("未登录");
        }
        if (ObjectUtils.isEmpty(searchOrderStateVo.getOrderNumber())) {
            return CommonResult.validateFailed("订单号不能为空");
        }
        if (ObjectUtils.isEmpty(searchOrderStateVo.getStatus())) {
            return CommonResult.validateFailed("查询方式不能为空");
        }
//        Long userId = 1L;
        Integer orderState = orderFrontService.searchOrderState(searchOrderStateVo.getOrderNumber(), userId, searchOrderStateVo.getStatus());
        if (ObjectUtils.isEmpty(orderState)) {
            return CommonResult.failure("查询失败",-1);
        }
        return CommonResult.success("success", orderState);
    }

    @ApiOperation("前端用户--个人中心--我的订单--分页查询")
    @GetMapping("/findPage")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页码", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页显示记录数", dataType = "int", paramType = "query"),
    })
    public CommonResult findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                                 @RequestParam(defaultValue = "5") Integer pageSize,
                                 HttpSession session) {
        // 用户id从session中自己拿
        Long userId = (Long) session.getAttribute("loginCId");
        if (ObjectUtils.isEmpty(userId)) {
            return CommonResult.unauthorized("未登录");
        }
        PageInfo<OrderGoFrontVo> orderGoFrontVoPageInfo = orderFrontService.findPage(pageNum, pageSize, userId);
        return CommonResult.success(orderGoFrontVoPageInfo);
    }

    @ApiOperation("前端用户查看订单详情")
    @GetMapping("/findById")
    @ApiParam(name = "订单id", value = "当前想要查看订单的id")
    public CommonResult findById(@RequestParam("id") Long id, HttpSession session) {
        if (ObjectUtils.isEmpty(id)) {
            return CommonResult.validateFailed("订单id为空");
        }
        // 用户id从session中自己拿
        Long userId = (Long) session.getAttribute("loginCId");
        if (ObjectUtils.isEmpty(userId)) {
            return CommonResult.unauthorized("未登录");
        }
        OrderFindByIdVo orderFindByIdVo = orderFrontService.findById(id, userId);
        return CommonResult.success(orderFindByIdVo);
    }

    @ApiOperation("前端用户--我的订单页面之取消订单功能")
    @PostMapping("/cancel")
    @ApiParam(name = "orderCancelVo", value = "微信支付vo类")
    public CommonResult cancel(@RequestBody OrderCancelVo orderCancelVo, HttpSession session) {
        if (ObjectUtils.isEmpty(orderCancelVo.getId())) {
            return CommonResult.validateFailed("订单id为空");
        }
        // 用户id从session中自己拿
        Long userId = (Long) session.getAttribute("loginCId");
        if (ObjectUtils.isEmpty(userId)) {
            return CommonResult.unauthorized("未登录");
        }
        int cancel = orderFrontService.cancel(orderCancelVo.getId(), userId);
        if (cancel == 1) {
            return CommonResult.success("取消订单成功");
        }
        return CommonResult.failure("取消订单失败");
    }

}
